package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.MeltCloudGroupsAndUserDTO;
import com.yami.shop.bean.dto.MeltCloudGroupsDTO;
import com.yami.shop.bean.enums.RongYunTypeEnum;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.vo.MeltCloudGroupsVo;
import com.yami.shop.bean.vo.MyFriendVo;
import com.yami.shop.bean.vo.UltraGroupApplyVO;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.PageUtil;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.dao.MeltCloudUltraGroupApplyMapper;
import com.yami.shop.dao.MeltCloudUserMapper;
import com.yami.shop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MeltCloudUserServiceImpl extends ServiceImpl<MeltCloudUserMapper, MeltCloudUser> implements MeltCloudUserService {
    @Autowired
    private MeltCloudGroupService groupService;
    @Autowired
    private MeltCloudGroupUserService groupUserService;
    @Autowired
    private UserSecurityConfigService userSecurityConfigService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private MeltCloudUserRemarkService userRemarkService;
    @Autowired
    private MeltCloudUltraGroupApplyMapper ultraGroupApplyMapper;
    @Autowired
    private UserService userService;
    
    /**
     * 注册融云用户
     *
     * @param meltCloudUser
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registeredRongYunUser(MeltCloudUser meltCloudUser) {
        this.save(meltCloudUser);
    }


    /**
     * 获取融云用户详细信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<MeltCloudUser> list(List<String> userId) {
        if (userId.size() != 0) {
            LambdaQueryWrapper<MeltCloudUser> wrapper = new LambdaQueryWrapper<MeltCloudUser>()
                    .in(MeltCloudUser::getId, userId);
            return this.list(wrapper);
        }else return null;
    }
    /**
     * 获取群组成员基本信息
     *
     * @param groupId
     * @return
     */
    @Override
    public List<MeltCloudUser> getGroupsUser(Long groupId) {
        List<MeltCloudUser> users = com.google.common.collect.Lists.newArrayList();
        MeltCloudGroup group = groupService.getById(groupId);
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getGroupId, groupId).eq(MeltCloudGroupUser::getIsDel,0);
        List<MeltCloudGroupUser> list = groupUserService.list(eq);
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, MeltCloudGroupUser> groupsUserMap = list.stream().collect(Collectors.toMap(MeltCloudGroupUser::getUserId, Function.identity()));
            List<String> meltUsers = list.stream().map(MeltCloudGroupUser::getUserId).collect(Collectors.toList());
            List<MeltCloudUser> userList = this.list(new LambdaQueryWrapper<MeltCloudUser>().in(MeltCloudUser::getId, meltUsers));

            if (CollectionUtil.isNotEmpty(userList))
                userList.forEach(user->{
                    //如果根据某个人在群组表查到记录，说明这个人是群组创建人
                    user.setGroupNikeName(groupsUserMap.get(user.getId()).getGroupNikeName());
                    user.setGroupCreator(user.getId().equals(group.getCreatorUserId()));
                    user.setStatus("1".equals(groupsUserMap.get(user.getId()).getUserStatus()));
                });
                users.addAll(userList);
        }
        return users;
    }

    /**
     * 昵称搜索
     * @param groupId
     * @param userName
     * @return
     */
    @Override
    public List<MeltCloudUser> getGroupsUser(Long groupId,String userName,String userId,Boolean isDel) {
        List<MeltCloudUser> users = com.google.common.collect.Lists.newArrayList();
        MeltCloudGroup group = groupService.getById(groupId);
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getGroupId, groupId)
                .eq(isDel,MeltCloudGroupUser::getIsDel,0)
                .orderByDesc(MeltCloudGroupUser::getIsManage);
        List<MeltCloudGroupUser> list = groupUserService.list(eq);
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, MeltCloudGroupUser> groupsUserMap = list.stream().collect(Collectors.toMap(MeltCloudGroupUser::getUserId, Function.identity()));
            List<String> meltUsers = list.stream().map(MeltCloudGroupUser::getUserId).collect(Collectors.toList());
            List<MeltCloudUser> userList = this.list(new LambdaQueryWrapper<MeltCloudUser>().in(MeltCloudUser::getId, meltUsers));
            Map<String, MeltCloudUser> userMap =  userList.stream().collect(Collectors.toMap(MeltCloudUser::getId, Function.identity()));
            if (CollectionUtil.isNotEmpty(userList)){
                userList.forEach(user->{
                    //如果根据某个人在群组表查到记录，说明这个人是群组创建人
                    if(StrUtil.isNotBlank(groupsUserMap.get(user.getId()).getGroupNikeName())){
                        user.setGroupNikeName(groupsUserMap.get(user.getId()).getGroupNikeName());
                    }else if(StrUtil.isBlank(groupsUserMap.get(user.getId()).getGroupNikeName())&&userMap.get(user.getId())!=null){
                        user.setGroupNikeName(userMap.get(user.getId()).getUserName());
                    }
                    user.setGroupCreator(user.getId().equals(group.getCreatorUserId()));
                    user.setStatus("1".equals(groupsUserMap.get(user.getId()).getUserStatus()));
                    user.setIsManage(groupsUserMap.get(user.getId()).getIsManage());
                });
                if(StrUtil.isNotEmpty(userName)){
                    List<String> existUserIds = new ArrayList<>();
                    if (StringUtils.isNotEmpty(userId)) {
                        List<MeltCloudUserRemark> userRemarks = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                                .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).like(MeltCloudUserRemark::getRemark, userName).in(MeltCloudUserRemark::getObjId, meltUsers));
                        existUserIds = userRemarks.stream().map(MeltCloudUserRemark::getObjId).collect(Collectors.toList());
                    }
                    List<String> finalExistUserIds = existUserIds;
                    userList = userList.stream().
                            filter(user ->  (
                                    StrUtil.isNotEmpty(user.getGroupNikeName()) && user.getGroupNikeName().contains(userName)
                                    || StrUtil.isNotEmpty(user.getUserName()) && user.getUserName().contains(userName)
                                    || CollUtil.isNotEmpty(finalExistUserIds) && finalExistUserIds.contains(user.getId())
                            ))
                            .sorted(Comparator.comparing(MeltCloudUser::isGroupCreator).thenComparing(MeltCloudUser::getIsManage).reversed())
                            .collect(Collectors.toList());
                }else{
                    userList = userList.stream().sorted(Comparator.comparing(MeltCloudUser::isGroupCreator).thenComparing(MeltCloudUser::getIsManage).reversed()).collect(Collectors.toList());
                }
                //获取用户和自己关系 确定私信是否开通
                if(StrUtil.isNotBlank(userId) && userList.size()>0){
                    List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                            .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, meltUsers));
                    Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
                    List<String> ids = userList.stream().map(s -> s.getId()).collect(Collectors.toList());
                    List<UserSecurityConfig> listConfig = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, ids));
                    Map<String, UserSecurityConfig> configMap = listConfig.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
                    List<MyFriendVo> relations = friendService.getRelations(ids, userId);
                    Map<String, MyFriendVo> userRelations = relations.stream().collect(Collectors.toMap(MyFriendVo::getId, Function.identity()));
                    userList.stream().forEach(meltCloudUser->{
                        if (StringUtils.isNotEmpty(remarkMap.get(meltCloudUser.getId()))) {
                            meltCloudUser.setGroupNikeName(remarkMap.get(meltCloudUser.getId()));
                        }
                        //添加是否对自己开通私聊
                        UserSecurityConfig userSecurityConfig = configMap.get(meltCloudUser.getId());
                        MyFriendVo myFriendVo = userRelations.get(meltCloudUser.getId());
                        if(ObjectUtil.isNotNull(userSecurityConfig)&&ObjectUtil.isNotNull(myFriendVo)){
                            meltCloudUser.setIsHasRealName(myFriendVo.getIsHasRealName());
                            meltCloudUser.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
                        }
                    });
                }
            }
            users.addAll(userList);
        }
        return users;
    }

    @Override
    public Map<String, MeltCloudUser> getUserInfoMap(Long groupId, String userId) {
        MeltCloudGroup group = groupService.getById(groupId);
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getGroupId, groupId);
        List<MeltCloudGroupUser> list = groupUserService.list(eq);
        Map<String, MeltCloudUser> usergroupMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, MeltCloudGroupUser> groupsUserMap = list.stream().collect(Collectors.toMap(MeltCloudGroupUser::getUserId, Function.identity()));
            List<String> meltUsers = list.stream().map(MeltCloudGroupUser::getUserId).collect(Collectors.toList());
            List<MeltCloudUser> userList = this.list(new LambdaQueryWrapper<MeltCloudUser>().in(MeltCloudUser::getId, meltUsers));
            if (CollectionUtil.isNotEmpty(userList)){
                Map<String, String> remarkMap = new HashMap<>();
                if (StringUtils.isNotEmpty(userId)) {
                    List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                            .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, meltUsers));
                    remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
                }
                Map<String, String> finalRemarkMap = remarkMap;
                userList.forEach(user->{
                    //如果根据某个人在群组表查到记录，说明这个人是群组创建人
                    if (StringUtils.isNotEmpty(userId) && finalRemarkMap.size() > 0 && StringUtils.isNotEmpty(finalRemarkMap.get(user.getId()))) {
                        user.setGroupNikeName(finalRemarkMap.get(user.getId()));
                    } else if (StringUtils.isNotEmpty(groupsUserMap.get(user.getId()).getGroupNikeName())){
                        user.setGroupNikeName(groupsUserMap.get(user.getId()).getGroupNikeName());
                    } else {
                        user.setGroupNikeName(user.getUserName());
                    }
                    user.setGroupCreator(user.getId().equals(group.getCreatorUserId()));
                    user.setStatus("1".equals(groupsUserMap.get(user.getId()).getUserStatus()));
                    user.setIsManage(groupsUserMap.get(user.getId()).getIsManage());
                });
            }
            usergroupMap =  userList.stream().collect(Collectors.toMap(MeltCloudUser::getId, Function.identity()));
        }
        return usergroupMap;
    }

    @Override
    public Map<String,Object> getUserInfoCount(Long groupId,Boolean isDel,String userId) {
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getGroupId, groupId);
        List<MeltCloudGroupUser> list = groupUserService.list(eq);
        MeltCloudGroup group = groupService.getById(groupId);
        Long count = 0l;
        if(isDel){
            count = list.stream().filter(s->"0".equals(s.getIsDel())).count();
        }else{
            count = Long.valueOf(list.size());
        }
        List<MeltCloudGroupUser> collect = list.stream().filter(s -> userId.equals(s.getUserId())).collect(Collectors.toList());
        if(collect.size()==1){
            group.setIsDismissMy(collect.get(0).getIsDel());
        }
        if (StringUtils.isNotEmpty(userId)) {
            MeltCloudUserRemark one = userRemarkService.getOne(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                    .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 2).eq(MeltCloudUserRemark::getObjId, groupId));
            if (one != null && StringUtils.isNotEmpty(one.getRemark()))
                group.setGroupRemark(one.getRemark());
        }
        if (group.getType().equals("1")) {
            PageParam<UltraGroupApplyVO> pageParam = new PageParam<UltraGroupApplyVO>();
            UltraGroupApplyVO applyVO = new UltraGroupApplyVO();
            applyVO.setGroupId(groupId);
            IPage<UltraGroupApplyVO> page = ultraGroupApplyMapper.page(pageParam, applyVO);
            if (CollUtil.isNotEmpty(page.getRecords())) {
                group.setApplyVO(page.getRecords().get(0));
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("count",count); // 群成员数量
        map.put("groupInfo",group);
        return map;
    }

    @Override
    public List<MeltCloudUser> getGroupsUser(Long groupId, List<String> userIds, String userName) {
        List<MeltCloudUser> users = com.google.common.collect.Lists.newArrayList();
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getGroupId, groupId)
                .in(MeltCloudGroupUser::getUserId, userIds);
        List<MeltCloudGroupUser> list = groupUserService.list(eq);
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> meltUsers = list.stream().map(MeltCloudGroupUser::getUserId).collect(Collectors.toList());
            List<MeltCloudUser> userList = this.list(new LambdaQueryWrapper<MeltCloudUser>()
                    .in(MeltCloudUser::getId, meltUsers)
                    .eq(StrUtil.isNotEmpty(userName), MeltCloudUser::getUserName, userName));
            if (CollectionUtil.isNotEmpty(userList))
                users.addAll(userList);
        }
        return users;
    }

    @Override
    public MeltCloudGroupsVo getDetail(List<MeltCloudGroupsDTO> groupsDto) {
        //返回对象
        List<MeltCloudUser> usersAll = Lists.newArrayList();
        List<MeltCloudGroup> groupsAll = Lists.newArrayList();
        Set<String> userIds =new HashSet<>();
        //获取群中用户id集合
        List<String> groupUserids = null;
        //单聊用户id集合
        List<String> oneuserids = null;
        //所有群对象
        List<MeltCloudGroup> groups = null;
        //所有群里群用户关系对象集合
        List<MeltCloudGroupUser> groupUsers = null;
        Map<String, List<MeltCloudGroupsDTO>> groupsMapDTOS = groupsDto.stream().collect(Collectors.groupingBy(MeltCloudGroupsDTO::getType));
        //1. 群组、群成员
        List<MeltCloudGroupsDTO> groupsDTOS = groupsMapDTOS.get(RongYunTypeEnum.GROUP.getType());
        if (CollectionUtil.isNotEmpty(groupsDTOS)) {
            //群id 集合
            List<Long> groupids = groupsDTOS.stream().map(a -> Long.parseLong(a.getId())).collect(Collectors.toList());
            //所有群里群用户关系对象集合
            groupUsers = groupUserService.list(new LambdaQueryWrapper<MeltCloudGroupUser>()
                    .in(MeltCloudGroupUser::getGroupId, groupids));
            //获取群中用户id集合
            groupUserids = groupUsers.stream().map(a ->a.getUserId()).collect(Collectors.toList());
            //所有群对象
            groups = groupService.list(groupids);
            userIds.addAll(groupUserids);
        }

        //单聊
        List<MeltCloudGroupsDTO> usersDTOS = groupsMapDTOS.get(RongYunTypeEnum.PRIVATE.getType());
       if(CollectionUtil.isNotEmpty(usersDTOS)){
           //单聊用户id集合
           oneuserids = usersDTOS.stream().map(MeltCloudGroupsDTO::getId).collect(Collectors.toList());
           userIds.addAll(oneuserids);
       }
        //所有用户对象
        List<MeltCloudUser> users = list(new ArrayList<>(userIds));
        //1. 群组
        if (CollectionUtil.isNotEmpty(users)&&CollectionUtil.isNotEmpty(groupsDTOS)) {
            //群对象 map 主键-》 MeltCloudGroup
            Map<Long, MeltCloudGroup> groupsMap = groups.stream().collect(Collectors.toMap(MeltCloudGroup::getId, Function.identity()));
            //群成员map  groupId -》 GroupUser
            Map<Long, List<MeltCloudGroupUser>> groupIdAndGroupUserMap = groupUsers.stream().collect(Collectors.groupingBy(MeltCloudGroupUser::getGroupId));
            //循环群对象
            groups.forEach(group -> {
                //获取该群 用户关系对象集合
                List<MeltCloudGroupUser> cloudGroupUsers = groupIdAndGroupUserMap.get(group.getId());
                //关系对象 map userid-》 MeltCloudGroupUser
                Map<String,MeltCloudGroupUser>  groupUserOne = cloudGroupUsers.stream().collect(Collectors.toMap(MeltCloudGroupUser::getUserId, Function.identity()));
                // 群成员
                List<String> thisUserIds = cloudGroupUsers.stream().map(s -> s.getUserId()).collect(Collectors.toList());
                List<MeltCloudUser> cloudUsers =  users.stream().filter(s->thisUserIds.contains(s.getId())).collect(Collectors.toList());
                //循环群用户对象
                cloudUsers.forEach(meltCloudUser -> {
                    MeltCloudGroup meltCloudGroup = groupsMap.get(group.getId());
                    MeltCloudGroupUser one = groupUserOne.get(meltCloudUser.getId());
                    meltCloudUser.setGroupNikeName(one.getGroupNikeName());
                    meltCloudUser.setStatus(one.getUserStatus().equals("1"));
                    meltCloudUser.setGroupCreator(meltCloudGroup.getCreatorUserId().equals(meltCloudUser.getId())?true:false);
                });
                group.setUsers(cloudUsers);
            });
            groupsAll.addAll(groups);
        }
        //2. 单聊
        if (CollectionUtil.isNotEmpty(users)&&CollectionUtil.isNotEmpty(usersDTOS)) {
            List<String> finalOneuserids = oneuserids;
            List<MeltCloudUser> data = users.stream().filter(s-> finalOneuserids.contains(s.getId())).collect(Collectors.toList());
            usersAll.addAll(data);
        }
        // 3.组成结果集
        MeltCloudGroupsVo vo = MeltCloudGroupsVo.builder()
                .users(users)
                .groups(groups)
                .build();
        return vo;
    }

    @Override
    public List<MeltCloudGroupsDTO> getConversationDetail(MeltCloudGroupsAndUserDTO meltCloudGroupsAndUser) {
        //返回对象
        Map<String,MeltCloudUser>  meltCloudUserMap = new HashMap<>();
        Map<Long,MeltCloudGroup>  meltCloudGroupMap = new HashMap<>();
        Map<String, List<MeltCloudGroupsDTO>> groupsMapDTOS = meltCloudGroupsAndUser.getGroups().stream().collect(Collectors.groupingBy(MeltCloudGroupsDTO::getType));
        String userId = meltCloudGroupsAndUser.getUserId();
        //1. 群组
        List<MeltCloudGroupsDTO> groupsDTOS = groupsMapDTOS.get(RongYunTypeEnum.GROUP.getType());
        //单聊
        List<MeltCloudGroupsDTO> usersDTOS = groupsMapDTOS.get(RongYunTypeEnum.PRIVATE.getType());
        //1. 群组
        if (CollectionUtil.isNotEmpty(groupsDTOS)) {
            //群id 集合
            List<Long> groupIds = groupsDTOS.stream().map(a -> Long.parseLong(a.getId())).collect(Collectors.toList());
            //群对象list
            List<MeltCloudGroup> groups = groupService.list(groupIds);
            //所有群备注
            List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                    .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 2).in(MeltCloudUserRemark::getObjId, groupIds));
            Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
            //当前用户在群内的个人信息
            List<MeltCloudGroupUser> ownGroupList = groupUserService.list(Wrappers.lambdaQuery(MeltCloudGroupUser.class).eq(MeltCloudGroupUser::getUserId, userId).in(MeltCloudGroupUser::getGroupId, groupIds));
            Map<Long, MeltCloudGroupUser> ownGroupMap = ownGroupList.stream().collect(Collectors.toMap(MeltCloudGroupUser::getGroupId, Function.identity()));
            //普通群聊头像
            List<Long> ordinaryGroupIds = groups.stream().filter(g -> g.getType().equals("0")).map(MeltCloudGroup::getId).collect(Collectors.toList());
            Map<Long, String> picsMap = null;
            if (CollUtil.isNotEmpty(ordinaryGroupIds)) {
                picsMap = groupService.ordinaryGroupPics(ordinaryGroupIds).stream().collect(Collectors.toMap(MeltCloudGroup::getId, MeltCloudGroup::getPics));
            }
            //循环群对象
            Map<Long, String> finalPicsMap = picsMap;
            groups.forEach(group -> {
                if (remarkMap.size() > 0 && StringUtils.isNotEmpty(remarkMap.get(group.getId().toString()))) {
                    group.setGroupName(remarkMap.get(group.getId().toString()));
                }
                if (Objects.nonNull(ownGroupMap.get(group.getId()))) {
                    group.setIsDismissMy(ownGroupMap.get(group.getId()).getIsDel());
                }
                if (group.getType().equals("0") && finalPicsMap != null && group.getIsOfficial()==0) {
                    group.setPics(finalPicsMap.get(group.getId()));
                }
            });
            meltCloudGroupMap = groups.stream().collect(Collectors.toMap(MeltCloudGroup::getId, Function.identity()));
        }
        //2. 单聊
        if (CollectionUtil.isNotEmpty(usersDTOS)) {
            List<String> userIds = usersDTOS.stream().map(MeltCloudGroupsDTO::getId).distinct().collect(Collectors.toList());
            List<MeltCloudUser> users = list(userIds);
            //备注名
            List<MeltCloudUserRemark> list = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                    .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, userIds));
            Map<String, String> userMap = list.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));

            List<User> userList = userService.listByIds(userIds);
            Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));

            users.forEach(u -> {
                u.setIsHasRealName(StringUtils.isNotEmpty(map.get(u.getId()).getRealName()));
                if (CollUtil.isNotEmpty(userMap) && StringUtils.isNotEmpty(userMap.get(u.getId()))) {
                    u.setUserName(userMap.get(u.getId()));
                }
            });
            meltCloudUserMap = users.stream().collect(Collectors.toMap(MeltCloudUser::getId, Function.identity()));
        }
        Map<Long, MeltCloudGroup> finalMeltCloudGroupMap = meltCloudGroupMap;
        Map<String, MeltCloudUser> finalMeltCloudUser = meltCloudUserMap;
        meltCloudGroupsAndUser.getGroups().forEach(meltCloudGroupsDTO->{
            if(meltCloudGroupsDTO.getType().equals(RongYunTypeEnum.GROUP.getType()) && ObjectUtils.isNotEmpty(finalMeltCloudGroupMap) && Objects.nonNull(finalMeltCloudGroupMap.get(Long.valueOf(meltCloudGroupsDTO.getId())))){
                try {
                    MeltCloudGroup meltCloudGroup = finalMeltCloudGroupMap.get(Long.valueOf(meltCloudGroupsDTO.getId()));
                    Map<String, Object> stringObjectMap = StringUtils.obj2MapNotNull(meltCloudGroup);
                    meltCloudGroupsDTO.setUserInfo(stringObjectMap);
                } catch (Exception e) {
                   log.info("查询异常");
                }
            }else if(meltCloudGroupsDTO.getType().equals(RongYunTypeEnum.PRIVATE.getType())  && ObjectUtils.isNotEmpty(finalMeltCloudUser) && Objects.nonNull(finalMeltCloudUser.get(meltCloudGroupsDTO.getId()))){
                try {
                    MeltCloudUser meltCloudUser = finalMeltCloudUser.get(meltCloudGroupsDTO.getId());
                    Map<String, Object> stringObjectMap = StringUtils.obj2MapNotNull(meltCloudUser);
                    meltCloudGroupsDTO.setUserInfo(stringObjectMap);
                } catch (Exception e) {
                    log.info("查询异常");
                }
            }
        });
        return meltCloudGroupsAndUser.getGroups();
    }


    /**
     * 群组列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<MeltCloudGroup> groups(String userId,String userName) {
        //查所在群成员对象
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getUserId, userId).eq(MeltCloudGroupUser::getIsDel,"0");
        List<MeltCloudGroupUser> groupAllUsers = groupUserService.list(eq);
        if (CollectionUtil.isNotEmpty(groupAllUsers)) {
            //查询所在的群ids
            List<Long> longs = groupAllUsers.stream().map(MeltCloudGroupUser::getGroupId).collect(Collectors.toList());
            //查询所在de的有效群对象
            LambdaQueryWrapper<MeltCloudGroup> groupseq = new LambdaQueryWrapper<MeltCloudGroup>().in(MeltCloudGroup::getId, longs).eq(MeltCloudGroup::getIsDismiss,"0").eq(MeltCloudGroup::getType, "0");
            if (StrUtil.isNotBlank(userName)) {
                List<MeltCloudUserRemark> list = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                        .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 2).in(MeltCloudUserRemark::getObjId, longs).like(MeltCloudUserRemark::getRemark, userName));
                if (CollUtil.isNotEmpty(list)) {
                    List<String> existGroupIds = list.stream().map(MeltCloudUserRemark::getObjId).collect(Collectors.toList());
                    groupseq.and(wp -> wp.like(MeltCloudGroup::getGroupName, userName).or().in(MeltCloudGroup::getId, existGroupIds));
                } else {
                    groupseq.like(MeltCloudGroup::getGroupName, userName);
                }
            }
            List<MeltCloudGroup> groups =  groupService.list(groupseq);
            if(groups.size()==0){
                return groups;
            }
            //获取有效的ids
            List<Long> groupIds = groups.stream().map(MeltCloudGroup::getId).collect(Collectors.toList());
            //获取有效的群用户对象
            LambdaQueryWrapper<MeltCloudGroupUser> groupUserssql = new LambdaQueryWrapper<MeltCloudGroupUser>()
                    .in(MeltCloudGroupUser::getGroupId, groupIds).eq(MeltCloudGroupUser::getIsDel,"0");
            List<MeltCloudGroupUser> groupUsers = groupUserService.list(groupUserssql);
            Map<Long, List<MeltCloudGroupUser>> groupUserMap = groupUsers.stream().collect(Collectors.groupingBy(MeltCloudGroupUser::getGroupId));
            //查询所有人
            List<String> userIds =groupUsers.stream().map(MeltCloudGroupUser::getUserId).distinct().collect(Collectors.toList());
            List<MeltCloudUser> cloudUsers = this.list(userIds);
            Map<String,MeltCloudUser>  userMap = cloudUsers.stream().collect(Collectors.toMap(MeltCloudUser::getId, Function.identity()));
            //群备注
            List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 2).in(MeltCloudUserRemark::getObjId, groupIds));
            Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
            //组装数据
            groups.forEach(meltCloudGroup -> {
                if (StringUtils.isNotEmpty(remarkMap.get(meltCloudGroup.getId().toString()))) {
                    meltCloudGroup.setGroupRemark(remarkMap.get(meltCloudGroup.getId().toString()));
                }
                List<MeltCloudGroupUser> mgroupUsers = groupUserMap.get(meltCloudGroup.getId());
                List<MeltCloudUser> lsit= Lists.newArrayList();
                mgroupUsers.forEach(s->{
                    MeltCloudUser meltCloudUser = userMap.get(s.getUserId());
                    if(meltCloudUser!=null){
                        meltCloudUser.setGroupNikeName(s.getGroupNikeName());
                        meltCloudUser.setStatus("1".equals(s.getUserStatus()));
                        meltCloudUser.setGroupCreator(meltCloudGroup.getCreatorUserId().equals(meltCloudUser.getId()));
                        lsit.add(meltCloudUser);
                    }
                });
                meltCloudGroup.setUsers(lsit);
            });
            return groups;
        }
        return Lists.newArrayList();
    }

    @Override
    public IPage<MeltCloudGroup> groupsPage(PageParam<MeltCloudGroup> page, String userId, String userName,Boolean ignoreProhibition) {
        ignoreProhibition= ignoreProhibition != null && ignoreProhibition;
        //查所在群成员对象
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getUserId, userId).eq(MeltCloudGroupUser::getIsDel,"0").eq(ignoreProhibition,MeltCloudGroupUser::getUserStatus, "0");
        List<MeltCloudGroupUser> groupAllUsers = groupUserService.list(eq);
        Page<MeltCloudGroup> groupPage = new PageParam<>();
        if (CollectionUtil.isNotEmpty(groupAllUsers)) {
            //查询所在的群ids
            List<Long> longs = groupAllUsers.stream().map(MeltCloudGroupUser::getGroupId).distinct().collect(Collectors.toList());
            //查询所在de的有效群对象
            LambdaQueryWrapper<MeltCloudGroup> groupseq = new LambdaQueryWrapper<MeltCloudGroup>()
                    .in(MeltCloudGroup::getId, longs).eq(MeltCloudGroup::getIsDismiss,"0")
                    .eq(MeltCloudGroup::getType, "0")
                    .eq(ignoreProhibition,MeltCloudGroup::getGroupStatus,"0")
                    .like(StrUtil.isNotBlank(userName),MeltCloudGroup::getGroupName,userName);
            groupPage = groupService.page(page, groupseq);
            List<MeltCloudGroup> groups = groupPage.getRecords();
            if(groups.size()==0){
                return groupPage;
            }
            //获取有效的ids
            List<Long> groupIds = groups.stream().map(MeltCloudGroup::getId).collect(Collectors.toList());
            //获取有效的群用户对象
            LambdaQueryWrapper<MeltCloudGroupUser> groupUserssql = new LambdaQueryWrapper<MeltCloudGroupUser>()
                    .in(MeltCloudGroupUser::getGroupId, groupIds).eq(MeltCloudGroupUser::getIsDel,"0");
            List<MeltCloudGroupUser> groupUsers = groupUserService.list(groupUserssql);
            Map<Long, List<MeltCloudGroupUser>> groupUserMap = groupUsers.stream().collect(Collectors.groupingBy(MeltCloudGroupUser::getGroupId));
            //查询所有人
            List<String> userIds =groupUsers.stream().map(MeltCloudGroupUser::getUserId).distinct().collect(Collectors.toList());
            List<MeltCloudUser> cloudUsers = this.list(userIds);
            Map<String,MeltCloudUser>  userMap = cloudUsers.stream().collect(Collectors.toMap(MeltCloudUser::getId, Function.identity()));
            //群备注
            List<MeltCloudUserRemark> list = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                    .eq(MeltCloudUserRemark::getUserId, userId).eq(MeltCloudUserRemark::getType, 2).in(MeltCloudUserRemark::getObjId, groupIds));
            Map<String, String> remarkMap = list.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
            //组装数据
            groups.forEach(meltCloudGroup -> {
                if (remarkMap.size() > 0 && StringUtils.isNotEmpty(remarkMap.get(meltCloudGroup.getId().toString()))) {
                    meltCloudGroup.setGroupName(remarkMap.get(meltCloudGroup.getId().toString()));
                }
                List<MeltCloudGroupUser> mgroupUsers = groupUserMap.get(meltCloudGroup.getId());
                List<MeltCloudUser> lsit= Lists.newArrayList();
                mgroupUsers.forEach(s->{
                    MeltCloudUser meltCloudUser = userMap.get(s.getUserId());
                    if(meltCloudUser!=null){
                        meltCloudUser.setGroupNikeName(s.getGroupNikeName());
                        meltCloudUser.setStatus("1".equals(s.getUserStatus()));
                        meltCloudUser.setGroupCreator(meltCloudGroup.getCreatorUserId().equals(meltCloudUser.getId()));
                        lsit.add(meltCloudUser);
                    }
                });
                meltCloudGroup.setUsers(lsit);
            });
            return groupPage;
        }
        return groupPage;
    }

    @Override
    public Long groupsCount(String userId, String userName) {
        //查所在群成员对象
        LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                .eq(MeltCloudGroupUser::getUserId, userId).eq(MeltCloudGroupUser::getIsDel,"0");
        List<MeltCloudGroupUser> groupAllUsers = groupUserService.list(eq);
        if (CollectionUtil.isNotEmpty(groupAllUsers)) {
            //查询所在的群ids
            List<Long> longs = groupAllUsers.stream().map(MeltCloudGroupUser::getGroupId).collect(Collectors.toList());
            //查询所在de的有效群对象
            LambdaQueryWrapper<MeltCloudGroup> groupseq = new LambdaQueryWrapper<MeltCloudGroup>()
                    .in(MeltCloudGroup::getId, longs).eq(MeltCloudGroup::getIsDismiss, "0").eq(MeltCloudGroup::getType, "0").like(StrUtil.isNotBlank(userName), MeltCloudGroup::getGroupName, userName);
            return groupService.count(groupseq);
        }
        return 0l;
    }

    /**
     * 获取群组成员
     *
     * @param pageDTO
     * @param userName
     * @param groupId
     * @param userIds
     * @return
     */
    @Override
    public PageVO<MeltCloudUser> getAll(PageDTO pageDTO, String userName, String groupId, List<String> userIds, String status) {
        PageVO<MeltCloudUser> vo = PageUtil.doPage(pageDTO, () -> baseMapper.getUsers(groupId, userIds, userName,status));
        MeltCloudGroup group = groupService.getById(groupId);
        vo.getList().forEach(meltCloudUser -> {
            if (group.getCreatorUserId().equals(meltCloudUser.getId()))
                meltCloudUser.setGroupCreator(true);

            LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                    .eq(MeltCloudGroupUser::getGroupId, groupId)
                    .eq(MeltCloudGroupUser::getUserId, meltCloudUser.getId());
            MeltCloudGroupUser one = groupUserService.getOne(eq);
            if (ObjectUtils.isNotEmpty(one)) {
                meltCloudUser.setStatus(one.getUserStatus().equals("1"));
                meltCloudUser.setIsManage(one.getIsManage());
            }
        });
        return vo;
    }
}
